<?php
/*
 *  Created by Andrew J. Bennieston on 2007-03-05.
 *  Copyright (c) 2007. All rights reserved.
 */

$_GLOBALS['PATH_DELIM'] = '/';
$_GLOBALS['ROOT_PATH'] = '/Users/stormhawk/Projects/PHP';
$_GLOBALS['SYSTEM_PATH'] = $_GLOBALS['ROOT_PATH'] . $_GLOBALS['PATH_DELIM'] . 'system';
$_GLOBALS['CLASS_PATH'] = $_GLOBALS['ROOT_PATH'] . $_GLOBALS['PATH_DELIM'] . 'classes';
$_GLOBALS['PLUGIN_PATH'] = $_GLOBALS['ROOT_PATH'] . $_GLOBALS['PATH_DELIM'] . 'plugins';
$_GLOBALS['TEMPLATE_PATH'] = $_GLOBALS['ROOT_PATH'] . $_GLOBALS['PATH_DELIM'] . 'templates';

// Build a path by gluing parts together with $_GLOBALS['PATH_DELIM']
function build_path(/*...varargs...*/)
{
	$args = func_get_args(); // func_get_args() depends on current scope so can't be used as a function parameter...
	return implode($_GLOBALS['PATH_DELIM'], $args);
}

require_once(build_path($_GLOBALS['SYSTEM_PATH'], 'Autoloader.php'));
$_GLOBALS['ClassLoaders'] = array();
$_GLOBALS['ClassLoader'] = new Autoloader('classes');

function register_loader($name, Autoloader $loader);
{
	$_GLOBALS['ClassLoaders'][$name] = $loader;
}

function unregister_loader($name)
{
	if ( array_key_exists($name, $_GLOBALS['ClassLoaders']) )
	{
		$_GLOBALS['ClassLoaders'] = array_diff_key($_GLOBALS['ClassLoaders'], array($name));
	}
}

function __autoload($class_name)
{
	$success = FALSE;
	try
	{
		$_GLOBALS['ClassLoader']->loadClass($class_name); // Try to load from CLASS_PATH first.
		$success = TRUE;
	}
	catch (AutoloaderException $e)
	{
		// The requested class could not be found in the CLASS_PATH
		// Try any registered Autoloader objects instead
		foreach ( $_GLOBALS['ClassLoaders'] as $scope => $classLoader )
		{
			try
			{
				$classLoader->loadClass($class_name);
				$success = TRUE;
				break;
			}
			catch ( AutoloaderException $e)
			{
				// Ignore and move on to the next loader
			}
		}
	}
	if ( ! success )
		throw new AutoloaderException('Class not found');
}

function force_load($scope, $class_name)
{
	// Don't catch the AutoloaderException here
	if ( array_key_exists($scope, $_GLOBALS['ClassLoaders']) )
	{
		$_GLOBALS['ClassLoaders'][$scope]->loadClass($class_name);
	}
}

?>